# -*- coding:UTF-8 -*-
from core.file import File
from files import *
from config.config import config


class FileType:

    @classmethod
    def file_types(cls):
        return [clazz.name for clazz in File.get_subclasses()]

    @classmethod
    def get_file_class(cls, clazz_name:str):
        classes = File.__subclasses__()
        if not clazz_name or not classes or len(classes) == 0:
            return None
        for clazz in classes:
            if clazz.name == clazz.name:
                return clazz


class FileSystem:
    def __init__(self, base:str):
        self.base = base
        self.files = set()
        self.load_files()

    def load_files(self):
        """
        加载已配置的File
        :return:
        """
        self.files = set()
        for name in FileType.file_types():
            if config.con.has_section(name):
                file_clazz = FileType.get_file_class(name)
                file = file_clazz(relative_path="", base=self.base, is_on_remote=True, is_on_local=False, size=0,
                           is_folder=True, sha=None)
                if file is not None and len(file.children) > 0:
                    self.files.add(file)

    def add_top_file(self, file:File):
        if file is not None and len(file.children) > 0:
            if self.files is not None and len(self.files):
                for f in self.files:
                    if f == file:
                        if f is None or len(f.children) > 0:
                            self.files.remove(f)
                            self.files.add(file)
                            return True
                        else:
                            return False
                    else:
                        self.files.add(file)
                        return True
            else:
                self.files.add(file)
                return True
        else:
            return False


    def get_top_file(self, file_type):
        if not self.files or len(self.files) == 0:
            return None
        for file in self.files:
            if isinstance(file, file_type):
                return file
        else:
            return None
